package com.gitee.fastmybatis.core.support;

import java.util.HashMap;
import java.util.Map;

public enum Dialect implements SqlWrapper {
    UNKNOWN,
    MYSQL,
    MICROSOFTSQLSERVER,
    ORACLE,
    POSTGRESQL,
    SQLITE,
    H2,
    DMDBMS,
    ;

    static final Map<Dialect, String> WRAP_MAP = new HashMap<>();

    static final String BACKQUOTE_WRAPPER = "`%s`";
    static final String DOUBLE_QUOTE_WRAPPER = "\"%s\"";
    static final String SQUARE_QUOTE_WRAPPER = "[%s]";

    static {
        WRAP_MAP.put(MYSQL, BACKQUOTE_WRAPPER);
        WRAP_MAP.put(SQLITE, BACKQUOTE_WRAPPER);
        WRAP_MAP.put(H2, BACKQUOTE_WRAPPER);

        WRAP_MAP.put(MICROSOFTSQLSERVER, SQUARE_QUOTE_WRAPPER);

        WRAP_MAP.put(ORACLE, DOUBLE_QUOTE_WRAPPER);
        WRAP_MAP.put(POSTGRESQL, DOUBLE_QUOTE_WRAPPER);
        WRAP_MAP.put(DMDBMS, DOUBLE_QUOTE_WRAPPER);
    }

    public static Dialect of(String dialect) {
        for (Dialect value : Dialect.values()) {
            if (value.name().equalsIgnoreCase(dialect)) {
                return value;
            }
        }
        return UNKNOWN;
    }

    @Override
    public String wrap(String sql) {
        String tpl = WRAP_MAP.get(this);
        if (tpl == null) {
            return sql;
        }
        return String.format(tpl, sql);
    }
}
